package terminal;


import Server.EventReceiver;

/*
 * Terminal.java
 *
 * Created on 17 de mayo de 2009, 17:00
 */
import Server.ClientListener;
import java.io.IOException;
import java.net.Socket;
import java.util.Calendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import org.json.JSONObject;

/**
 *
 * @author  Administrador
 */
public class Terminal extends javax.swing.JFrame implements EventReceiver{

    /** Creates new form Terminal */
    public Terminal() throws IOException {
        initComponents();

        ClientListener listener = new ClientListener(7000,7010, this);
        listener.start();
        
         //tabla.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        TableColumn col = tabla.getColumnModel().getColumn(0);
        col.setMaxWidth(80);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tabla = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Arrivals / Departures");
        getContentPane().setLayout(new javax.swing.BoxLayout(getContentPane(), javax.swing.BoxLayout.LINE_AXIS));

        tabla.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Vuelo Nro", "Estado"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tabla.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(tabla);
        tabla.getColumnModel().getColumn(0).setMinWidth(90);
        tabla.getColumnModel().getColumn(0).setPreferredWidth(100);

        getContentPane().add(jScrollPane1);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    new Terminal().setVisible(true);
                } catch (IOException ex) {
                    Logger.getLogger(Terminal.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tabla;
    // End of variables declaration//GEN-END:variables


    public void receiveMessage(String strMessage, Socket socket) {
          
          System.out.println(strMessage);
        try {
            actualizarDatosEnPantalla(strMessage);
        } catch (Exception ex) {
            Logger.getLogger(Terminal.class.getName()).log(Level.SEVERE, null, ex);
        }                    
    }
    
   private void actualizarDatosEnPantalla(String strMessage) throws Exception {
       
        DefaultTableModel tm = (DefaultTableModel)tabla.getModel();

        // leemos los datos del vuelo desde el mensaje
        JSONObject msg = new JSONObject(strMessage);
        String strIds[] = msg.getNames(msg);
    
        String estado;
        int flightId;
        JSONObject jEstado;
 
        while (tm.getRowCount()>0)
            tm.removeRow(0);
        
        for(int i=0; i<strIds.length; i++){
            jEstado = msg.getJSONObject(strIds[i]);
            estado = jEstado.getString("state");
            flightId = jEstado.getInt("flightId");                        
            tm.insertRow(tabla.getRowCount(), new Object[]{flightId, estado});
        }

        this.setTitle("Arrivals/Departures - " + timeToString(Calendar.getInstance()));

    }

      private String timeToString(Calendar cHoraActual) {
        String s = cHoraActual.get(Calendar.DAY_OF_MONTH) + "/" +
                   cHoraActual.get(Calendar.MONTH) + "/" +
                   cHoraActual.get(Calendar.YEAR) + "@"+
                   cHoraActual.get(Calendar.HOUR_OF_DAY) + ":"+
                   cHoraActual.get(Calendar.MINUTE);
        return s;
    }
}


